<script lang="ts" setup>
import { ref, onMounted, computed } from "vue";
import { v4 as uuidv4 } from "uuid";

const canvas = ref<HTMLCanvasElement | null>(null);
const container = ref<HTMLElement | null>(null);
const ctx = ref();
const canvasWidth = ref(800);
const canvasHeight = ref(0);

const isShow = ref(true);
const scrollTop = ref(0);
const rowHeight = ref(50);
const visibleRows = 20;
const totalItems = 1000000;
const dataList = Array.from({ length: totalItems }, (_, i) => ({
  id: uuidv4(),
  name: "",
  content: `Item ${i}`,
}));
console.log(dataList);

let visibleData = computed(() => {
  const startIndex = Math.floor(scrollTop.value / rowHeight.value);
  const endIndex = startIndex + visibleRows;
  console.log(startIndex, endIndex);
  console.log(dataList.slice(startIndex, endIndex));
  return dataList.slice(startIndex, endIndex);
});
// 初始化画布
const initCanvas = () => {
  if (canvas.value) {
    ctx.value = canvas.value.getContext("2d");
    render();
  }
};
// 绑定滚动事件
const bindEvents = () => {
    console.log("绑定滚动事件");
  if (!container.value) return;
  container.value.addEventListener("scroll", handleScroll);
};
// 处理滚动
const handleScroll = () => {
  if (!container.value) return;
  scrollTop.value = container.value.scrollTop;
  render();
};
// 渲染可见区域的数据
const render = () => {
  console.log("渲染可见区域的数据", visibleData.value);
  console.log(typeof visibleData.value);
  ctx.value.clearRect(0, 0, canvasWidth.value, canvasHeight.value);
  visibleData.value.forEach((row, index) => {
    const y = index * rowHeight.value - (scrollTop.value % rowHeight.value);
    ctx.value.fillText(row, 10, y + rowHeight.value / 2);
  });
};
onMounted(() => {
  console.log(document.documentElement.clientWidth);
  console.log(window);
  canvasWidth.value = document.documentElement.clientWidth;
  canvasHeight.value = document.documentElement.clientHeight;
  setTimeout(() => {
    initCanvas();
    bindEvents();
  }, 350);
});
</script>
<template>
  <template v-if="isShow">
    <div class="canvas-table-container" ref="container">
      <canvas ref="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
    </div>
  </template>
  <template v-else>
    <div>
      <ul>
        <li v-for="(item, index) in dataList" :key="item.id">
          {{ item.id }} -- {{ item.content }}
        </li>
      </ul>
    </div></template
  >
</template>
